package org.soft.xinyu.equipmentmanagement.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.soft.xinyu.equipmentmanagement.entity.WswMachine;
import org.soft.xinyu.equipmentmanagement.result.Result;
import org.soft.xinyu.equipmentmanagement.service.WswMachineService;
import org.soft.xinyu.equipmentmanagement.utils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: xinyu
 * @Date: 2021/12/22/20:38
 * @Description:
 */
@RestController
@RequestMapping("/excel")
public class ExcelTestController {

    @Autowired
    private WswMachineService wswMachineService;

    @GetMapping("/exportWswMachineList")
    public void exportWswMachineList(
            @RequestParam List<Integer> ids,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
        String dt = df.format(new Date());
        List<WswMachine> list = null;
        if (ids.size() > 0 && !ids.isEmpty()) {
            list = wswMachineService.list(new QueryWrapper<WswMachine>().in("id", ids));
        } else {
            list = wswMachineService.list();
        }
        //设置Excel表头
        String[] title = {"ID", "设备编号", "设备名称", "规格型号", "出厂编号", "生产厂家", "资产编号", "购入价格", "购入日期", "启用时间", "设备管理员", "采购人"
                , "验收人", "责任人", "尺寸", "功率", "净重", "运行状态", "存放位置", "检定标志位", "检定周期", "检定日期（最后一次检定覆盖）", "有效期至", "送检单位"
                , "技术指标", "设备系统记录创建时间"};
        //设置Excel文件名
        String filename = "设备列表_" + dt + ".xls";
        //设置工作表名称
        String sheetName = "sheet1";
        //开始对从数据库中获取到的数据进行处理
        String[][] content = new String[list.size()][title.length];
        try {
            for (int i = 0; i < list.size(); i++) {
                content[i][0] = String.valueOf(list.get(i).getId());
                content[i][1] = list.get(i).getMachineId();
                content[i][2] = list.get(i).getMachineName();
                content[i][3] = list.get(i).getMachineModel();
                content[i][4] = list.get(i).getFactoryNumber();
                content[i][5] = list.get(i).getManufacture();
                content[i][6] = list.get(i).getAssetNumber();
                content[i][7] = list.get(i).getPrice();
                String purchaseDate = "";
                if (list.get(i).getPurchaseDate() == null || "".equals(list.get(i).getPurchaseDate())) {
                    purchaseDate = " ";
                } else {
                    purchaseDate = list.get(i).getPurchaseDate().toString();
                }
                content[i][8] = purchaseDate;
                String startDate = "";
                if (list.get(i).getStartDate() == null || "".equals(list.get(i).getStartDate())) {
                    startDate = " ";
                } else {
                    startDate = list.get(i).getStartDate().toString();
                }
                content[i][9] = startDate;
                content[i][10] = list.get(i).getAdministrator();
                content[i][11] = list.get(i).getPurchaser();
                content[i][12] = list.get(i).getAcceptor();
                content[i][13] = list.get(i).getPersonLiable();
                content[i][14] = list.get(i).getSize();
                content[i][15] = list.get(i).getPower();
                content[i][16] = list.get(i).getWeight();
                content[i][17] = list.get(i).getRunningState();
                content[i][18] = list.get(i).getStorageLocation();
                if (list.get(i).getTestBool() == "0" || "0".equals(list.get(i).getTestBool())) {
                    content[i][19] = "不需要检定";
                } else {
                    content[i][19] = "需要检定";
                }
                content[i][20] = list.get(i).getTestCycle();
                String testDate = "";
                if (list.get(i).getTestDate() == null || "".equals(list.get(i).getTestDate())) {
                    testDate = " ";
                } else {
                    testDate = list.get(i).getTestDate().toString();
                }
                content[i][21] = testDate;
                String termOfValidity = "";
                if (list.get(i).getTermOfValidity() == null || "".equals(list.get(i).getTermOfValidity())) {
                    termOfValidity = " ";
                } else {
                    termOfValidity = list.get(i).getStartDate().toString();
                }
                content[i][22] = termOfValidity;
                content[i][23] = list.get(i).getInspectionEnterprise();
                content[i][24] = list.get(i).getTechnicalIndicators();
                content[i][25] = list.get(i).getCreateTime().toString();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        try {
            // 响应到客户端
            this.setResponseHeader(response, filename);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向客户端发送响应流方法
     *
     * @param response
     * @param fileName
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
